﻿using System.Text.Json;
using AntQuartzUI.Model;
using AntQuartzUI.Services;
using AntQuartzUI.Services.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json.Linq;

namespace AntQuartzUI.Pages;

public class Home : PageModel
{
    private readonly IQuartzService _quartzService;
    
    
    public Home(IQuartzService quartzService)
    {
        _quartzService = quartzService;
    }
    
    public void OnGet()
    {
        
    }

    public async Task<IActionResult> OnGetJobPageList()
    {
        return new JsonResult(await _quartzService.GetAllJobStatusesAsync());
    }
    
    public async Task<IActionResult> OnPostPauseTrigger()
    {
        var rep = new ResponseModel(200,"成功");
        
        try
        {
            using var reader = new StreamReader(Request.Body);
            var body = await reader.ReadToEndAsync();
            var json = JObject.Parse(body);

            var triggerName = json["triggerName"]?.ToString();
            var triggerGroup = json["triggerGroup"]?.ToString();

            await _quartzService.PauseTriggerAsync(triggerName, triggerGroup);
        }
        catch (Exception e)
        {
            rep.Message = e.Message;
            rep.Result = 500;
        }

        return new JsonResult(rep);
    }
    
    public async Task<IActionResult> OnPostStartTrigger()
    {
        var rep = new ResponseModel(200,"成功");
        
        try
        {
            using var reader = new StreamReader(Request.Body);
            var body = await reader.ReadToEndAsync();
            var json = JObject.Parse(body);

            var triggerName = json["triggerName"]?.ToString();
            var triggerGroup = json["triggerGroup"]?.ToString();

            await _quartzService.StartTriggerAsync(triggerName, triggerGroup);
        }
        catch (Exception e)
        {
            rep.Message = e.Message;
            rep.Result = 500;
        }
        
        return new JsonResult(rep);
    }
}